package com.champChooser.panels
{
	import com.champChooser.components.nancy.nancy;
	import com.champChooser.constants.CCConstants;
	import com.champChooser.constants.ImageConstants;
	
	import flash.net.SharedObject;
	
	import mx.collections.ArrayCollection;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.TextInput;
	import mx.controls.TileList;
	import mx.controls.Tree;
	import mx.core.Application;
	import mx.events.ListEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	public class LogggedInViewPanel extends VBox
	{
		public function LogggedInViewPanel()
		{
		}
		
		public var tree1:Tree;
		/* public var tree2:Tree; */
		public var teamNancy:nancy;
		public var removePlayerFromTeam:Button;
		public var addPlayerToTeam:Button;
		public var txtPlayerSearch:TextInput;
		
		[Bindable]
		public var dpBatsmen:ArrayCollection;
		[Bindable]
		public var dpBowlers:ArrayCollection;
		[Bindable]
		public var dpAllRounder:ArrayCollection;
		[Bindable]
		public var dpWicketKeeper:ArrayCollection;
		[Bindable]
		public var dpPlayersListTree:ArrayCollection;
		
		private var dpAllPlayers:ArrayCollection;
		
		public var playerService:HTTPService;
		public var searchPlayerService:HTTPService;
		public var usersTeamPlayerService:HTTPService;
		public var updateToTeamService:HTTPService;
		
		public var bowlersTileList:TileList;
		public var wicketKeeperTileList:TileList;
		public var allRounderTileList:TileList;
		public var batsmenTileList:TileList;
		
		public  const url:String = "http://"+CCConstants.SERVER_IP+"/ChampChooser/core/services/player/playerListService.php";
		public  const searchUrl:String = "http://"+CCConstants.SERVER_IP+"/ChampChooser/core/services/player/searchPlayerListService.php";
		public  const usersTeamPlayersUrl:String = "http://"+CCConstants.SERVER_IP+"/ChampChooser/core/services/user/userTeamService.php";
		public  const updateToTeamServiceUrl:String = "http://"+CCConstants.SERVER_IP+"/ChampChooser/core/services/team/UpdateToTeamService.php";
			
		private const PHP_PLAYERID_PARAM:String = "playerId";
		private const PHP_PLAYER_SEARCH_FILTER_PARAM:String = "filterString";
		private const PHP_USER_ID_PARAM:String = "userId";
		private const PHP_TEAM_ID_PARAM:String = "teamId";
		private const PHP_PLAYER_IDS_PARAM:String = "playerIds";
		
		protected function resultHandler(event:ResultEvent):void{
		  	var players: ArrayCollection = event.result.records.record as ArrayCollection;
		  	if(players==null){
		  		players = new ArrayCollection();
		  	}
		  	tree1.dataProvider = players;
		}
		
		protected function searchHandler(event:ResultEvent):void{
		  	var players: ArrayCollection = event.result.records.record as ArrayCollection;
		  	if(players==null){
		  		players = new ArrayCollection();
		  	}
		  	tree1.dataProvider = players;
		}
		
		protected function usersTeamPlayersResultHandler(event:ResultEvent):void{
		  	var players: ArrayCollection = event.result.records.record.player as ArrayCollection;
		  	
		  	dpBatsmen = new ArrayCollection();
		  	dpBowlers = new ArrayCollection();
		  	dpAllRounder = new ArrayCollection();
		  	dpWicketKeeper = new ArrayCollection();
		  	dpAllPlayers = new ArrayCollection();
		  	
		  	if(players!=null){
		  		
		  		for each (var node:Object in players){
		  			dpAllPlayers.addItem(node);
					switch(node.playerType){
						case 'Batsman':
							dpBatsmen.addItem(node);
							break;	
						case 'Bowler':
							dpBowlers.addItem(node);
							break;
						case 'AllRounder':
							dpAllRounder.addItem(node);
							break;
						case 'WicketKeeper':
							dpWicketKeeper.addItem(node);
							break;
					}
				}
		  	}
		  	/* tree2.dataProvider = players; */
		}
		
		protected function updateToTeamServiceHandler(event:ResultEvent):void{
			sendUsersTeamPlayerService();
			Alert.show("Team saved successfully");
		}
		
		protected function faultHandler(event:FaultEvent):void{
			Alert.show(event.toString(),"OOPS");
		}
		
		protected function getPlayerStats(event:ListEvent):void{
			var selectedNode:Object = event.currentTarget.selectedItem;
			var params:Object = {};
			if(selectedNode!=null){
				params[PHP_PLAYERID_PARAM] = selectedNode.id;;
				teamNancy.loadStats.send(params);
			}
		}
		
		protected function saveTeam():void{
			var selectedNodes:ArrayCollection = new ArrayCollection()/* tree2.selectedItems */;
			var object:Object;
			
			if(dpBatsmen!=null && dpBatsmen.length>0){
				for each(object in dpBatsmen){
					selectedNodes.addItem(object);
				}
			}
			
			if(dpBowlers!=null && dpBowlers.length>0){
				for each(object in dpBowlers){
					selectedNodes.addItem(object);
				}
			}
			
			if(dpAllRounder!=null && dpAllRounder.length>0){
				for each(object in dpAllRounder){
					selectedNodes.addItem(object);
				}
			}
			
			if(dpWicketKeeper!=null && dpWicketKeeper.length>0){
				for each(object in dpWicketKeeper){
					selectedNodes.addItem(object);
				}
			}
			
			if(selectedNodes!=null && selectedNodes.length==11){
				// TODO fix this... validations
				// Alert.show("Trying to add "+selectedNodes.length +" players");
				var params:Object = {};
				var ids:String = "";
				for each (var node:Object in selectedNodes){
					ids = ids + node.id + ",";
				}
				
				ids=ids.substr(0,ids.length-1);
				var user:SharedObject = CCConstants.getLoggedInUser();
				params[PHP_TEAM_ID_PARAM] = user.data.currentTeam;
				params[PHP_PLAYER_IDS_PARAM] = ids;
				//searchPlayerService.send(params);
				updateToTeamService.send(params);
			}else if(selectedNodes.length!=11 || 
				dpBatsmen.length!=CCConstants.TEAM_BATSMEN_LIMIT ||
				dpBowlers.length!=CCConstants.TEAM_BOWLERS_LIMIT ||
				dpAllRounder.length!=CCConstants.TEAM_ALLROUNDERS_LIMIT ||
				dpWicketKeeper.length!=CCConstants.TEAM_WICKETKEEPERS_LIMIT){
				Alert.show("Please select 11 players to save a team:" + 
						"\n"+CCConstants.TEAM_BATSMEN_LIMIT+" Batsmen" + 
						"\n"+CCConstants.TEAM_BOWLERS_LIMIT+" Bowlers" + 
						"\n"+CCConstants.TEAM_ALLROUNDERS_LIMIT+" All Rounder" + 
						"\n"+CCConstants.TEAM_WICKETKEEPERS_LIMIT+" Wicket Keeper");
			}
		}
		
		private function doesPlayerExist(node:Object):Boolean{
			for each (var player:Object in dpAllPlayers){
				if(player.id==node.id){
					Alert.show("Player already exists in your team!","IGNORING " + node.fname + " "+ node.lname);
					return false;
				}
			}
			return true;
		}
		
		protected function addPlayer():void{
			var selectedNodes:Array = tree1.selectedItems;
			if(selectedNodes!=null && selectedNodes.length!=0){
                for each (var node:Object in selectedNodes){
                	if(doesPlayerExist(node)){
						switch(node.playerType){
							case CCConstants.PLAYER_TYPE_BATSMAN:
								if(dpBatsmen.length>=CCConstants.TEAM_BATSMEN_LIMIT){
									Alert.show(CCConstants.TEAM_BATSMEN_LIMIT+" Batsmen already added","IGNORING " + node.fname + " "+ node.lname);
									break;
								}
								dpBatsmen.addItem(node);
								break;	
							case CCConstants.PLAYER_TYPE_BOWLER:
								if(dpBowlers.length>=CCConstants.TEAM_BOWLERS_LIMIT){
									Alert.show(CCConstants.TEAM_BOWLERS_LIMIT+" Bowlers already added","IGNORING " + node.fname + " "+ node.lname);
									break;
								}
								dpBowlers.addItem(node);
								break;
							case CCConstants.PLAYER_TYPE_ALLROUNDER:
								if(dpAllRounder.length>=CCConstants.TEAM_ALLROUNDERS_LIMIT){
									Alert.show(CCConstants.TEAM_ALLROUNDERS_LIMIT+" All Rounder already added","IGNORING " + node.fname + " "+ node.lname);
									break;
								}
								dpAllRounder.addItem(node);
								break;
							case CCConstants.PLAYER_TYPE_WICKETKEEPER:
								if(dpWicketKeeper.length>=CCConstants.TEAM_WICKETKEEPERS_LIMIT){
									Alert.show(CCConstants.TEAM_WICKETKEEPERS_LIMIT+" Wicket Keeper already added","IGNORING " + node.fname + " "+ node.lname);
									break;
								}
								dpWicketKeeper.addItem(node);
								break;
						}
                	}
				}
			}else{
				Alert.show("Please select player(s) to add to team");
			}
		}
		
		protected function removePlayers():void{
			var selectedNodes:ArrayCollection = new ArrayCollection()/* tree2.selectedItems */;
			var object:Object;
			
			if(batsmenTileList!=null && batsmenTileList.selectedItems!=null && batsmenTileList.selectedItems.length>0){
				for each(object in batsmenTileList.selectedItems){
					selectedNodes.addItem(object);
				}
			}
			
			if(bowlersTileList!=null && bowlersTileList.selectedItems!=null && bowlersTileList.selectedItems.length>0){
				for each(object in bowlersTileList.selectedItems){
					selectedNodes.addItem(object);
				}
			}
			
			if(allRounderTileList!=null && allRounderTileList.selectedItems!=null && allRounderTileList.selectedItems.length>0){
				for each(object in allRounderTileList.selectedItems){
					selectedNodes.addItem(object);
				}
			}
			
			if(wicketKeeperTileList!=null && wicketKeeperTileList.selectedItems!=null && wicketKeeperTileList.selectedItems.length>0){
				for each(object in wicketKeeperTileList.selectedItems){
					selectedNodes.addItem(object);
				}
			}
			
			if(selectedNodes==null && selectedNodes.length==0){
				Alert.show("Please select player(s) to remove");
				return;
			}
			
			var object2:Object;
			var index:int;
			for each (object2 in selectedNodes){
				try{
					dpBatsmen.removeItemAt(dpBatsmen.getItemIndex(object2));
				}catch(e:Error){
					
				}
				try{
					dpBowlers.removeItemAt(dpBowlers.getItemIndex(object2));
				}catch(e:Error){
					
				}
				try{
					dpAllRounder.removeItemAt(dpAllRounder.getItemIndex(object2));
				}catch(e:Error){
					
				}
				try{
					dpWicketKeeper.removeItemAt(dpWicketKeeper.getItemIndex(object2));
				}catch(e:Error){
					
				}
			}
			
			Alert.show(selectedNodes.length + " player(s) removed successfully!");
		}
		
		protected function showDetailedStats():void{
			var selectedNodes:Array = tree1.selectedItems;
			if(selectedNodes!=null && selectedNodes.length!=0){
				Application.application.currentState = "viewStates";
			}else{
				Alert.show("Please select player(s)");
			}
		}
		
		protected function filterPlayerResults():void{
			var params:Object = {};
			params[PHP_PLAYER_SEARCH_FILTER_PARAM] = txtPlayerSearch.text;
			searchPlayerService.send(params);
		}
		
		public function sendUsersTeamPlayerService():void{
			var params:Object = {};
			
			var userId:String = CCConstants.getLoggedInUser().data.userId;
			if(userId!=null && userId!=''){
				params[PHP_USER_ID_PARAM] = userId;
				usersTeamPlayerService.send(params);
			}
		}
		
		public function tree_labelFunc(item:Object):String{
			var label:String = new String("");
			label = label + item.fname + " " + item.lname + "\n"+ item.playerType +"\n(cost - " + item.cost + ", points - " + item.points + ")";
			return label;
		}
		
		public function tree_iconFunc(item:Object):Class {
            var iconClass:Class;
            
            switch (item.country) {
                case CCConstants.COUNTRY_NAME_AUSTRALIA:
                    iconClass = ImageConstants.FLAG_AUSTRALIA;
                    break;
                case CCConstants.COUNTRY_NAME_BANGLADESH:
                    iconClass = ImageConstants.FLAG_BANGLADESH;
                    break;
                case CCConstants.COUNTRY_NAME_ENGLAND:
                    iconClass = ImageConstants.FLAG_ENGLAND;
                    break;
                case CCConstants.COUNTRY_NAME_INDIA:
                    iconClass = ImageConstants.FLAG_INDIA;
                    break;
                case CCConstants.COUNTRY_NAME_NEWZELAND:
                    iconClass = ImageConstants.FLAG_NEWZELAND;
                    break;
                case CCConstants.COUNTRY_NAME_PAKISTAN:
                    iconClass = ImageConstants.FLAG_PAKISTAN;
                    break;
                case CCConstants.COUNTRY_NAME_SOUTHAFRICA:
                    iconClass = ImageConstants.FLAG_SOUTHAFRICA;
                    break;
                case CCConstants.COUNTRY_NAME_SRILANKA:
                    iconClass = ImageConstants.FLAG_SRILANKA;
                    break;
                case CCConstants.COUNTRY_NAME_WESTINDIES:
                    iconClass = ImageConstants.FLAG_WESTINDIES;
                    break;
                case CCConstants.COUNTRY_NAME_ZIMBABWE:
                    iconClass = ImageConstants.FLAG_ZIMBABWE;
                	break;
                default:
                	iconClass = ImageConstants.FLAG_CANADA;
                	break;
            }
            return iconClass;
        }
	}
}